package com.cyn.controller.rabbitmq.config;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;
 
@Component
public class OrderRevicer {
 
	@RabbitListener(bindings = @QueueBinding(
			value = @Queue(value = "order-queue", durable = "true"), 
			exchange = @Exchange(value = "order-exchange", durable = "true", type = "direct"), 
			key = "order.add"))
	@RabbitHandler
	public void onOrderMessage(@Payload Order order, @Headers Map<String, Object> headers, Channel channel)
			throws Exception {
		System.err.println("-----------收到消息---------------");
		System.err.println("订单ID：" + order.getId());
		Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
		System.err.println(deliveryTag);
		try {
			// 成功
			// void basicAck(long deliveryTag, boolean multiple)
			// deliveryTag:该消息的index
			// multiple：是否批量. true：将一次性ack所有小于deliveryTag的消息。
			// ACK
			int i=1/0;
			channel.basicAck(deliveryTag, true);
			System.err.println(channel.isOpen());
		} catch (Exception e) {
			// 失败
			// channel.basicNack(long deliveryTag, boolean multiple, boolean requeue);
			// requeue：被拒绝的是否重新入队列。

			// channel.basicReject(long deliveryTag, boolean requeue);
			// channel.basicNack 与 channel.basicReject
			// 的区别在于basicNack可以批量拒绝多条消息，而basicReject一次只能拒绝一条消息。

			// 重新放入队列

			channel.basicNack(deliveryTag, false, true);
			// 抛弃此条消息
//			 channel.basicNack(deliveryTag, false, false);
		}

	}
}